//
//  CedarMenuScrollView.m
//  StarOrangeStaff
//z
//  Created by lshenrong on 2020/6/29.
//  Copyright © 2020 lshenrong. All rights reserved.
//

#import "CedarMenuScrollView.h"

@implementation CedarMenuScrollView
{
    UIView *_lastView;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.showsHorizontalScrollIndicator = NO;
        _currentButtonIndex = 0; // 默认当前选择的按钮是第一个
    }
    return self;
}

#pragma mark - 赋值标题数组
/** 赋值标题数组 */
- (void)setTitleArray:(NSArray *)titleArray{
    _titleArray = titleArray;
    
    // 先将所有子控件移除
    for (UIView *subView in self.subviews) {
        [subView removeFromSuperview];
    }
    
    // 将lastView置空
    _lastView = nil;
    
    // 遍历标题数组
    [_titleArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self addSubview:menuButton];
        if (_lastView) {
            menuButton.frame = CGRectMake(CGRectGetMaxX(_lastView.frame) + 50, 0, 80, self.height);
        }else{
            menuButton.frame = CGRectMake(kMarginOffsetX * 2, 0, 80, self.height);
        }
        
        menuButton.tag = 100 + idx;
        menuButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [menuButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [menuButton setTitleColor:kLightBlackColor forState:UIControlStateNormal];
        [menuButton setTitleColor:kBlackColor forState:UIControlStateSelected];
        [menuButton setTitle:obj forState:UIControlStateNormal];
        [menuButton addTarget:self action:@selector(menuButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        // 宽度自适应
        [menuButton sizeToFit];
        menuButton.height = self.height;
        // 这句不能少，不然初始化时button的label的宽度为0
        [menuButton layoutIfNeeded];
        
        // 默认第一个按钮时选中状态
        if (idx == 0) {
            menuButton.selected = YES;
            [menuButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
            [menuButton layoutIfNeeded];
            [menuButton sizeToFit];
        }
        
        _lastView = menuButton;
    }];
    
    self.contentSize = CGSizeMake(CGRectGetMaxX(_lastView.frame) + 15, CGRectGetHeight(self.frame));
}

#pragma mark - 菜单按钮点击
/** 菜单按钮点击 */
- (void)menuButtonClicked:(UIButton *)sender{
    // 改变按钮的选中状态和字体大小
    for (UIButton *button in self.subviews) {
        if ([button isMemberOfClass:[UIButton class]]) {
            button.selected = NO;
            

        }
    }
    sender.selected = YES;
}

@end
